#include "xhtmlplayer.h"
#include <xwritelogexport.h>
#include <qwebview.h>
#include <qtimer.h>
#include <qwebframe.h>

XHtmlPlayer::XHtmlPlayer(QWidget* parent, Qt::WFlags f)
	:QWidget(parent, Qt::FramelessWindowHint|Qt::WStyle_StaysOnTop),
	 m_timeout(0),m_tmShortPage(NULL),m_webview(NULL), m_webframe(NULL)
{
	this->setCursor(Qt::BlankCursor);
	m_webview = new QWebView(this);
	m_webframe = m_webview->page()->mainFrame();
	m_webframe->setScrollBarPolicy (Qt::Vertical, Qt::ScrollBarAlwaysOff);
	m_webframe->setScrollBarPolicy (Qt::Horizontal, Qt::ScrollBarAlwaysOff);

	QPalette pal = this->palette();
	pal.setColor(this->backgroundRole(), Qt::white);
	this->setPalette(pal);
	m_tmShortPage = new QTimer(this);
	connect (m_tmShortPage, SIGNAL(timeout()), this, SLOT(onHtmlPlayDone()));
	m_tmShortPage->stop();
	connect (m_webview, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));

}
/* ========================================================================
 * ================  SIGNAL-SLOT  =========================================
 * ========================================================================*/
void XHtmlPlayer::onHtmlPlayDone()
{
	LOG_E("==============================");
	LOG_E("[Finish] HTML TIMER : ID=%02d", m_index);
	LOG_E("===============================");
	m_tmShortPage->stop();
	disconnect(m_tmShortPage, SIGNAL(timeout()), this, SLOT(onHtmlPlayDone()));
//	LOG_E("[EMIT TO] XLayoutManager");
	emit sgPlayHtmlDone(m_index);
}
void XHtmlPlayer::onLoadFinished(bool)
{
	m_tmShortPage->start(m_timeout);
	m_webview->show();
	this->show();
}

/* =========================================================================
 * ================  PUBLIC FUNCTION =======================================
 * =========================================================================*/
int XHtmlPlayer::stopPlay()
{
	m_tmShortPage->stop();
	m_webview->hide();
	disconnect (m_tmShortPage, SIGNAL(timeout()), this, SLOT(onHtmlPlayDone()));
	return 0;
}
void XHtmlPlayer::playHtml(const char* file, const int timeout, const int index)
{
	m_index = index;
	assert (NULL!=file);
	LOG_E(" ---- [ Playing HTML File] -----");
	m_timeout = timeout;
	LOG_E("File:[%s], id:[%02d], timeout:[%02d]",file,m_index,m_timeout);
	m_webview->load(QUrl::fromLocalFile(file));
	m_timeout = timeout;
	connect (m_tmShortPage, SIGNAL(timeout()), this, SLOT(onHtmlPlayDone()));
	m_tmShortPage->start(m_timeout);
}
void XHtmlPlayer::setPlayerGeometry(const int startX, const int startY, const int width, const int height)
{
	setGeometry(QRect(startX, startY, width, height));
	m_webview->resize(width,height);
	return;
}
